<?php


namespace app\guild\controller;


use app\common\model\LiveCategoryModel;
use app\common\model\LiveHistoryModel;
use app\common\model\LiveModel;
use app\common\model\UserModel;
use think\db\Query;
use think\facade\Request;

class LiveController extends BaseController
{

    /**
     * 直播监控
     * @return mixed
     */
    public function dashboard()
    {
        $page  = Request::param('page') ?? 1;
        $limit = 12;

        // 所属代理员工
        $gulid_idarr = $this->getGuildUserId();
        $lives       = array();
        $count       = 0;
        if ($gulid_idarr) {
            $where = [
                ['anchorid', 'in', $gulid_idarr]
            ];
            $lives = LiveModel::where($where)->with('anchor')->order(['id' => 'desc'])->limit(($page - 1) * $limit, $limit)->select();
            $count = LiveModel::where($where)->count('*');
        }

        $this->assign('lives', $lives);
        $this->assign('page', $page);
        $this->assign('limit', $limit);
        $this->assign('count', $count);
        return $this->fetch();
    }


    private function checkManager()
    {
        if (!in_array($this->guild_manager->mobile, config('other.guild_view_live'))) {
            if (Request::isAjax()) {
                return self::bulidFail("没有相关内容");
            } else {
                $this->error('没有相关内容', url('index/index'));
            }
        }
    }

    /**
     * 获取直播列表数据
     * @return \think\response\Json
     */
    public function index()
    {
        $categorys = LiveCategoryModel::where("status", 1)->order('sort', 'asc')->order('id', 'desc')->select();
        return $this->assign(['categorys' => $categorys])->fetch();
    }


    public function getlives()
    {
        $field = 'id,anchorid,title,thumb,categoryid,start_stamp,matchid,category,pull_flv_url,status';
        $model = LiveModel::field($field);
        $model = $model->whereIn('anchorid', parent::getGuildUserId());
        if ($anchorid = Request::get('anchorid')) {
            $model = $model->where('anchorid', $anchorid);
        }
        if ($categoryid = Request::get('categoryid')) {
            $model = $model->where('categoryid', $categoryid);
        }

        return json([
            "count" => $model->count('id'),
            "data"  => $model->with([
                'anchor'   => function (Query $query) {
                    $query->field('id, nick_name');
                },
                'matches'  => function (Query $query) {
                    $query->field('match_id, comp,home,away');
                },
                'category' => function (Query $query) {
                    $query->field('id, title');
                }
            ])->page(Request::get('page', 1), Request::get('limit', 20))
                ->order("id", "desc")
                ->select()->each(function ($query) {
                    if ($query->start_stamp > 0) {
                        $query->start_stamp = date('Y-m-d H:i:s', $query->start_stamp);
                    }
                })->toArray(),
            "code"  => 0,
            "msg"   => "",
        ]);
    }

    /**
     * 历史直播
     * @return \think\response\Json
     */

    public function history()
    {
        return $this->fetch();
    }

    public function get_history()
    {
        $anchor_id = Request::param("anchorid");
        $nick_name = Request::param("nick_name");
        $page      = Request::param("page");
        $limit     = Request::param("limit");

        $where = [];
        if ($anchor_id) {
            $where[] = ['anchorid', '=', is_numeric($anchor_id) ? $anchor_id : 0];
        }

        if (mb_strlen($nick_name) > 0) {
            $u_where[] = ['nick_name', 'like', "%{$nick_name}%"];
            $uid_arr   = UserModel::where($u_where)->column('id');
            $where[]   = ['anchorid', 'in', $uid_arr];
        }

        $field = 'id,anchorid,liveid,title,categoryid,start_stamp,end_stamp,matchid';

        $list = LiveHistoryModel::with([
            'anchor'   => function ($query) {
                $query->field('id,nick_name,account');
            },
            'category' => function ($query) {
                $query->field('id,title');
            },
            'matches'  => function ($query) {
                $query->field('id,match_id,comp,home,away');
            }
        ])->where($where)
            ->whereIn('anchorid', parent::getGuildUserId())
            ->field($field)
            ->page($page, $limit)
            ->order('id DESC')
            ->select();

        if (count($list) > 0) {
            $count = LiveHistoryModel::where($where)->count();

            foreach ($list as &$item) {
                $item->start_stamp_str = $item->start_stamp > 0 ? date('Y-m-d H:i:s', $item->start_stamp) : '';
                $item->end_stamp_str   = $item->end_stamp > 0 ? date('Y-m-d H:i:s', $item->end_stamp) : '';
                $item->live_minute     = '';

                $diff = intval($item->end_stamp - $item->start_stamp);
                if ($diff > 0) {
                    $h = floor($diff / 3600);
                    $i = floor($diff % 3600 / 60);
                    $s = floor($diff % 3600 % 60);

                    $item->live_minute = $h . '小时 ' . $i . '分 ' . $s . '秒';
                }
            }

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }
}
